//
//  DMConfigReader.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/1/27.
//

#import "DMConfigReader.h"
#import "IMJSONUtils.h"
#import "../Logger/IMLogUtils.h"

#pragma mark - 广告配置模型实现

@implementation DMAdUnitConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMAdUnitConfig: type=%@, unitID=%@, isLow=%@>", 
            self.ad_type, self.ad_unitID, self.is_low ? @"YES" : @"NO"];
}

@end

@implementation DMTAConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMTAConfig: serverURL=%@, appId=%@>", 
            self.server_url, self.app_id];
}

@end

@implementation DMAdjustConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMAdjustConfig: appToken=%@, iapToken=%@>", 
            self.app_token, self.sdk_iap_revenue_token];
}

@end

@implementation DMFBConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMFBConfig: appId=%@, clientToken=%@>", 
            self.facebook_AppId, self.facebook_client_token];
}

@end

@implementation DMOdeeoConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMOdeeoConfig: appId=%@>", self.app_id];
}

@end

@implementation DMConfigAdConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMConfigAdConfig: defaultSDK=%@, banners=%lu, inters=%lu, rewards=%lu>", 
            self.default_sdk_type, 
            (unsigned long)self.BannerIds.count,
            (unsigned long)self.InterIds.count,
            (unsigned long)self.RewardIds.count];
}

@end

@implementation DMIAPProductConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMIAPProductConfig: productId=%@, price=%@>", 
            self.productId, self.dollar_price];
}

@end

@implementation DMIAPConfig

- (NSString *)description {
    return [NSString stringWithFormat:@"<DMIAPConfig: consumables=%lu, nonConsumables=%lu, subscriptions=%lu>", 
            (unsigned long)self.consumableIds.count,
            (unsigned long)self.nonConsumableIds.count,
            (unsigned long)self.subscribeIds.count];
}

@end

#pragma mark - 配置读取器实现

@interface DMConfigReader ()

@property (nonatomic, strong) NSDictionary *configData;        // 原始配置数据
@property (nonatomic, strong) NSString *currentFilePath;       // 当前配置文件路径
@property (nonatomic, strong) NSDate *loadTime;                // 配置加载时间
@property (nonatomic, strong) DMTAConfig *cachedTAConfig;      // 缓存的TA配置
@property (nonatomic, strong) DMAdjustConfig *cachedAdjustConfig; // 缓存的Adjust配置
@property (nonatomic, strong) DMFBConfig *cachedFBConfig;      // 缓存的FB配置
@property (nonatomic, strong) DMConfigAdConfig *cachedAdConfig;      // 缓存的广告配置
@property (nonatomic, strong) DMIAPConfig *cachedIAPConfig;    // 缓存的IAP配置

@end

@implementation DMConfigReader

#pragma mark - 单例

+ (instancetype)sharedInstance {
    static DMConfigReader *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[DMConfigReader alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 初始化配置读取器"];
    }
    return self;
}

#pragma mark - 配置加载

- (BOOL)loadConfig {
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 开始从默认路径加载配置"];
    
    // 尝试从Bundle中加载
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"sdk_config_mediation" ofType:@"json"];
    if (bundlePath) {
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 找到Bundle中的配置文件: %@", bundlePath];
        return [self loadConfigFromPath:bundlePath];
    }
    
    // 尝试从SDK Bundle中加载
    NSString *sdkBundlePath = [self getSDKConfigPath];
    if (sdkBundlePath) {
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 找到SDK中的配置文件: %@", sdkBundlePath];
        return [self loadConfigFromPath:sdkBundlePath];
    }
    
    [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 未找到配置文件"];
    return NO;
}

- (BOOL)loadConfigFromPath:(NSString *)filePath {
    if (!filePath || filePath.length == 0) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 配置文件路径为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 从路径加载配置: %@", filePath];
    
    // 检查文件是否存在
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 配置文件不存在: %@", filePath];
        return NO;
    }
    
    // 读取文件内容
    NSError *error;
    NSString *jsonString = [NSString stringWithContentsOfFile:filePath 
                                                      encoding:NSUTF8StringEncoding 
                                                         error:&error];
    if (error) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 读取配置文件失败: %@", error.localizedDescription];
        return NO;
    }
    
    if (!jsonString || jsonString.length == 0) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 配置文件内容为空"];
        return NO;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 配置文件大小: %lu 字节", (unsigned long)jsonString.length];
    
    // 解析JSON
    NSDictionary *configDict = [IMJSONUtils objectFromJSONString:jsonString];
    if (!configDict || ![configDict isKindOfClass:[NSDictionary class]]) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 配置文件JSON解析失败"];
        return NO;
    }
    
    // 保存配置数据
    self.configData = configDict;
    self.currentFilePath = filePath;
    self.loadTime = [NSDate date];
    
    // 清除缓存
    [self clearCache];
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 配置加载成功，版本: %@", [self sdkVersion]];
    
    // 验证配置
    if ([self validateConfig]) {
        [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 配置验证通过"];
    } else {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置验证失败，可能存在缺失的必要字段"];
    }
    
    return YES;
}

- (BOOL)loadConfigFromBundle:(NSString *)fileName {
    if (!fileName || fileName.length == 0) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] Bundle文件名为空"];
        return NO;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 从Bundle加载配置: %@", fileName];
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"];
    if (!filePath) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] Bundle中未找到配置文件: %@.json", fileName];
        return NO;
    }
    
    return [self loadConfigFromPath:filePath];
}

- (BOOL)reloadConfig {
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 重新加载配置"];
    
    if (!self.currentFilePath) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 没有当前配置文件路径，使用默认加载方式"];
        return [self loadConfig];
    }
    
    return [self loadConfigFromPath:self.currentFilePath];
}

#pragma mark - 私有方法

- (NSString *)getSDKConfigPath {
    // 获取SDK Bundle中的配置文件路径
    NSString *bundlePath = [[NSBundle bundleForClass:[self class]] resourcePath];
    if (bundlePath) {
        NSString *configPath = [bundlePath stringByAppendingPathComponent:@"sdk_config_mediation.json"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:configPath]) {
            return configPath;
        }
    }
    return nil;
}

- (void)clearCache {
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 清除配置缓存"];
    self.cachedTAConfig = nil;
    self.cachedAdjustConfig = nil;
    self.cachedFBConfig = nil;
    self.cachedAdConfig = nil;
    self.cachedIAPConfig = nil;
}

#pragma mark - 基础配置获取

- (NSString *)sdkVersion {
    NSString *version = [IMJSONUtils safeStringFromDictionary:self.configData forKey:@"sdk_version"];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取配置版本: %@", version];
    return version;
}

- (NSString *)appName {
    NSString *appName = [IMJSONUtils safeStringFromDictionary:self.configData forKey:@"app_name"];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取应用名称: %@", appName];
    return appName;
}

- (NSString *)packageName {
    NSString *packageName = [IMJSONUtils safeStringFromDictionary:self.configData forKey:@"package_name"];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取包名: %@", packageName];
    return packageName;
}

- (NSString *)sdkAppId {
    NSString *sdkAppId = [IMJSONUtils safeStringFromDictionary:self.configData forKey:@"sdk_app_id"];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取SDK应用ID: %@", sdkAppId];
    return sdkAppId;
}

- (NSString *)appstoreId {
    NSString *appstoreId = [IMJSONUtils safeStringFromDictionary:self.configData forKey:@"AppstoreId"];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取AppStore ID: %@", appstoreId];
    return appstoreId;
}

- (NSString *)appVersion {
    id shortVersionObj = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    NSString *shortVersion = ([shortVersionObj isKindOfClass:[NSString class]]) ? (NSString *)shortVersionObj : nil;
    if (shortVersion && shortVersion.length > 0) {
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取应用版本: %@", shortVersion];
        return shortVersion;
    }
    id buildVersionObj = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
    NSString *buildVersion = ([buildVersionObj isKindOfClass:[NSString class]]) ? (NSString *)buildVersionObj : nil;
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取应用构建版本: %@", buildVersion];
    return buildVersion;
}

#pragma mark - 第三方服务配置

- (DMTAConfig *)taConfig {
    if (self.cachedTAConfig) {
        return self.cachedTAConfig;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析TA配置"];
    
    NSDictionary *taDict = [IMJSONUtils safeDictionaryFromDictionary:self.configData forKey:@"ta_config"];
    if (!taDict) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] TA配置不存在"];
        return nil;
    }
    
    DMTAConfig *config = [[DMTAConfig alloc] init];
    config.server_url = [IMJSONUtils safeStringFromDictionary:taDict forKey:@"server_url"];
    config.app_id = [IMJSONUtils safeStringFromDictionary:taDict forKey:@"app_id"];
    
    self.cachedTAConfig = config;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] TA配置解析完成: %@", config];
    
    return config;
}

- (DMAdjustConfig *)adjustConfig {
    if (self.cachedAdjustConfig) {
        return self.cachedAdjustConfig;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析Adjust配置"];
    
    NSDictionary *adjustDict = [IMJSONUtils safeDictionaryFromDictionary:self.configData forKey:@"adjust_config"];
    if (!adjustDict) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] Adjust配置不存在"];
        return nil;
    }
    
    DMAdjustConfig *config = [[DMAdjustConfig alloc] init];
    config.app_token = [IMJSONUtils safeStringFromDictionary:adjustDict forKey:@"app_token"];
    config.sdk_iap_revenue_token = [IMJSONUtils safeStringFromDictionary:adjustDict forKey:@"sdk_iap_revenue_token"];
    
    self.cachedAdjustConfig = config;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] Adjust配置解析完成: %@", config];
    
    return config;
}

- (DMFBConfig *)fbConfig {
    if (self.cachedFBConfig) {
        return self.cachedFBConfig;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析Facebook配置"];
    
    NSDictionary *fbDict = [IMJSONUtils safeDictionaryFromDictionary:self.configData forKey:@"fb_config"];
    if (!fbDict) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] Facebook配置不存在"];
        return nil;
    }
    
    DMFBConfig *config = [[DMFBConfig alloc] init];
    config.facebook_AppId = [IMJSONUtils safeStringFromDictionary:fbDict forKey:@"facebook_AppId"];
    config.facebook_client_token = [IMJSONUtils safeStringFromDictionary:fbDict forKey:@"facebook_client_token"];
    
    self.cachedFBConfig = config;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] Facebook配置解析完成: %@", config];
    
    return config;
}

#pragma mark - 广告配置获取

+ (NSString *)auctionId {
    // 生成 UUID
    NSString *uuid = [[NSUUID UUID] UUIDString];
    
    // 获取当前毫秒时间戳
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSince1970];
    long long milliseconds = (long long)(timeInterval * 1000);
    
    // 拼接 UUID 和毫秒时间戳
    NSString *auctionId = [NSString stringWithFormat:@"%@_%lld", uuid, milliseconds];
    
    return auctionId;
}

- (DMConfigAdConfig *)adConfig {
    if (self.cachedAdConfig) {
        return self.cachedAdConfig;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析广告配置"];
    
    NSDictionary *adDict = [IMJSONUtils safeDictionaryFromDictionary:self.configData forKey:@"ad_config"];
    if (!adDict) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 广告配置不存在"];
        return nil;
    }
    
    DMConfigAdConfig *config = [[DMConfigAdConfig alloc] init];
    config.default_sdk_type = [IMJSONUtils safeStringFromDictionary:adDict forKey:@"default_sdk_type"];
    config.IS_AppKey = [IMJSONUtils safeStringFromDictionary:adDict forKey:@"IS_AppKey"];
    config.GADApplicationIdentifier = [IMJSONUtils safeStringFromDictionary:adDict forKey:@"GADApplicationIdentifier"];
    config.Max_AppKey = [IMJSONUtils safeStringFromDictionary:adDict forKey:@"Max_AppKey"];
    config.max_review_api_key = [IMJSONUtils safeStringFromDictionary:adDict forKey:@"max_review_api_key"];
    
    // 解析广告单元配置
    config.BannerIds = [self parseAdUnitConfigs:[IMJSONUtils safeArrayFromDictionary:adDict forKey:@"BannerIds"] type:@"Banner"];
    config.InterIds = [self parseAdUnitConfigs:[IMJSONUtils safeArrayFromDictionary:adDict forKey:@"InterIds"] type:@"Inter"];
    config.SplashIds = [self parseAdUnitConfigs:[IMJSONUtils safeArrayFromDictionary:adDict forKey:@"SplashIds"] type:@"Splash"];
    config.RewardIds = [self parseAdUnitConfigs:[IMJSONUtils safeArrayFromDictionary:adDict forKey:@"RewardIds"] type:@"Reward"];
    config.NativeIds = [self parseAdUnitConfigs:[IMJSONUtils safeArrayFromDictionary:adDict forKey:@"NativeIds"] type:@"Native"];
    
    // 解析Odeeo配置
    NSDictionary *odeeoDict = [IMJSONUtils safeDictionaryFromDictionary:adDict forKey:@"odeeoConfig"];
    if (odeeoDict) {
        DMOdeeoConfig *odeeoConfig = [[DMOdeeoConfig alloc] init];
        odeeoConfig.app_id = [IMJSONUtils safeStringFromDictionary:odeeoDict forKey:@"app_id"];
        odeeoConfig.audio_icon_placement_id = [IMJSONUtils safeStringFromDictionary:odeeoDict forKey:@"audio_icon_placement_id"];
        odeeoConfig.audio_banner_placement_id = [IMJSONUtils safeStringFromDictionary:odeeoDict forKey:@"audio_banner_placement_id"];
        odeeoConfig.audio_rewarded_icon_placement_id = [IMJSONUtils safeStringFromDictionary:odeeoDict forKey:@"audio_rewarded_icon_placement_id"];
        odeeoConfig.audio_rewarded_banner_placement_id = [IMJSONUtils safeStringFromDictionary:odeeoDict forKey:@"audio_rewarded_banner_placement_id"];
        config.odeeoConfig = odeeoConfig;
    }
    
    self.cachedAdConfig = config;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 广告配置解析完成: %@", config];
    
    return config;
}

- (NSArray<DMAdUnitConfig *> *)parseAdUnitConfigs:(NSArray *)configArray type:(NSString *)type {
    if (!configArray || configArray.count == 0) {
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] %@广告配置为空", type];
        return @[];
    }
    
    NSMutableArray<DMAdUnitConfig *> *configs = [NSMutableArray array];
    
    for (NSDictionary *configDict in configArray) {
        if (![configDict isKindOfClass:[NSDictionary class]]) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] %@广告配置项格式错误", type];
            continue;
        }
        
        DMAdUnitConfig *config = [[DMAdUnitConfig alloc] init];
        config.ad_type = [IMJSONUtils safeStringFromDictionary:configDict forKey:@"ad_type"];
        config.ad_unitID = [IMJSONUtils safeStringFromDictionary:configDict forKey:@"primaryad_unitID"];
        config.is_low = [IMJSONUtils safeBoolFromDictionary:configDict forKey:@"is_low"];
        
        if (config.ad_type && config.ad_unitID) {
            [configs addObject:config];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析%@广告配置: %@", type, config];
        } else {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] %@广告配置缺少必要字段", type];
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] %@广告配置解析完成，共%lu个", type, (unsigned long)configs.count];
    return [configs copy];
}

- (NSString *)defaultSDKType {
    return [[self adConfig] default_sdk_type];
}

- (NSArray<DMAdUnitConfig *> *)bannerAdConfigs {
    return [[self adConfig] BannerIds];
}

- (NSArray<DMAdUnitConfig *> *)interstitialAdConfigs {
    return [[self adConfig] InterIds];
}

- (NSArray<DMAdUnitConfig *> *)splashAdConfigs {
    return [[self adConfig] SplashIds];
}

- (NSArray<DMAdUnitConfig *> *)rewardedAdConfigs {
    return [[self adConfig] RewardIds];
}

- (NSArray<DMAdUnitConfig *> *)nativeAdConfigs {
    return [[self adConfig] NativeIds];
}

- (DMAdUnitConfig *)adUnitConfigForType:(NSString *)adType sdkType:(NSString *)sdkType isLow:(BOOL)isLow {
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 查找广告配置: type=%@, sdk=%@, isLow=%@", adType, sdkType, isLow ? @"YES" : @"NO"];
    
    NSArray<DMAdUnitConfig *> *configs = nil;
    
    if ([adType isEqualToString:@"Banner"]) {
        configs = [self bannerAdConfigs];
    } else if ([adType isEqualToString:@"Inter"]) {
        configs = [self interstitialAdConfigs];
    } else if ([adType isEqualToString:@"Splash"]) {
        configs = [self splashAdConfigs];
    } else if ([adType isEqualToString:@"Reward"]) {
        configs = [self rewardedAdConfigs];
    } else if ([adType isEqualToString:@"Native"]) {
        configs = [self nativeAdConfigs];
    } else {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未知的广告类型: %@", adType];
        return nil;
    }
    
    for (DMAdUnitConfig *config in configs) {
        if ([config.ad_type isEqualToString:sdkType] && config.is_low == isLow) {
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 找到匹配的广告配置: %@", config];
            return config;
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到匹配的广告配置"];
    return nil;
}

#pragma mark - SDK Key获取

- (NSString *)ironSourceAppKey {
    NSString *key = [[self adConfig] IS_AppKey];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取IronSource AppKey: %@", key];
    return key;
}

- (NSString *)googleAdApplicationIdentifier {
    NSString *identifier = [[self adConfig] GADApplicationIdentifier];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取Google广告应用标识符: %@", identifier];
    return identifier;
}

- (NSString *)maxAppKey {
    NSString *key = [[self adConfig] Max_AppKey];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取MAX AppKey: %@", key];
    return key;
}

- (NSString *)maxReviewApiKey {
    NSString *key = [[self adConfig] max_review_api_key];
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取MAX审核API Key: %@", key];
    return key;
}

#pragma mark - IAP配置获取

- (nullable DMIAPConfig *)iapConfig {
    if (self.cachedIAPConfig) {
        return self.cachedIAPConfig;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析IAP配置"];
    
    NSDictionary *iapDict = [IMJSONUtils safeDictionaryFromDictionary:self.configData forKey:@"IAP_Config"];
    if (!iapDict) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] IAP配置不存在"];
        return nil;
    }
    
    DMIAPConfig *config = [[DMIAPConfig alloc] init];
    config.consumableIds = [self parseIAPProductConfigs:[IMJSONUtils safeArrayFromDictionary:iapDict forKey:@"consumableIds"] type:@"消耗品"];
    config.nonConsumableIds = [self parseIAPProductConfigs:[IMJSONUtils safeArrayFromDictionary:iapDict forKey:@"nonConsumableIds"] type:@"非消耗品"];
    config.subscribeIds = [self parseIAPProductConfigs:[IMJSONUtils safeArrayFromDictionary:iapDict forKey:@"subscribeIds"] type:@"订阅"];
    
    self.cachedIAPConfig = config;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] IAP配置解析完成: %@", config];
    
    return config;
}

- (NSArray<DMIAPProductConfig *> *)parseIAPProductConfigs:(NSArray *)configArray type:(NSString *)type {
    if (!configArray || configArray.count == 0) {
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] %@IAP配置为空", type];
        return @[];
    }
    
    NSMutableArray<DMIAPProductConfig *> *configs = [NSMutableArray array];
    
    for (NSDictionary *configDict in configArray) {
        if (![configDict isKindOfClass:[NSDictionary class]]) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] %@IAP配置项格式错误", type];
            continue;
        }
        
        DMIAPProductConfig *config = [[DMIAPProductConfig alloc] init];
        config.productId = [IMJSONUtils safeStringFromDictionary:configDict forKey:@"productId"];
        config.dollar_price = [IMJSONUtils safeStringFromDictionary:configDict forKey:@"dollar_price"];
        
        if (config.productId && config.dollar_price) {
            [configs addObject:config];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 解析%@IAP配置: %@", type, config];
        } else {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] %@IAP配置缺少必要字段", type];
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] %@IAP配置解析完成，共%lu个", type, (unsigned long)configs.count];
    return [configs copy];
}

- (NSArray<DMIAPProductConfig *> *)consumableProducts {
    return [[self iapConfig] consumableIds];
}

- (NSArray<DMIAPProductConfig *> *)nonConsumableProducts {
    return [[self iapConfig] nonConsumableIds];
}

- (NSArray<DMIAPProductConfig *> *)subscriptionProducts {
    return [[self iapConfig] subscribeIds];
}

- (DMIAPProductConfig *)productConfigForId:(NSString *)productId {
    if (!productId || productId.length == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 产品ID为空"];
        return nil;
    }
    
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 查找产品配置: %@", productId];
    
    // 在消耗品中查找
    for (DMIAPProductConfig *config in [self consumableProducts]) {
        if ([config.productId isEqualToString:productId]) {
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 在消耗品中找到产品配置: %@", config];
            return config;
        }
    }
    
    // 在非消耗品中查找
    for (DMIAPProductConfig *config in [self nonConsumableProducts]) {
        if ([config.productId isEqualToString:productId]) {
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 在非消耗品中找到产品配置: %@", config];
            return config;
        }
    }
    
    // 在订阅产品中查找
    for (DMIAPProductConfig *config in [self subscriptionProducts]) {
        if ([config.productId isEqualToString:productId]) {
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 在订阅产品中找到产品配置: %@", config];
            return config;
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到产品配置: %@", productId];
    return nil;
}

#pragma mark - 配置状态

- (BOOL)isConfigLoaded {
    BOOL loaded = (self.configData != nil);
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 配置加载状态: %@", loaded ? @"已加载" : @"未加载"];
    return loaded;
}

- (NSString *)configFilePath {
    return self.currentFilePath;
}

- (NSDate *)configLoadTime {
    return self.loadTime;
}

- (BOOL)validateConfig {
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 开始验证配置完整性"];
    
    if (!self.configData) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 配置数据为空"];
        return NO;
    }
    
    BOOL isValid = YES;
    
    // 验证基础配置
    NSString *version = [self sdkVersion];
    if (!version || version.length == 0 || [version isEqualToString:@"0"]) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置版本无效"];
        isValid = NO;
    }
    
    if (![self appName] || [[self appName] length] == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 应用名称缺失"];
        isValid = NO;
    }
    
    if (![self packageName] || [[self packageName] length] == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 包名缺失"];
        isValid = NO;
    }
    
    if (![self sdkAppId] || [[self sdkAppId] length] == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] SDK应用ID缺失"];
        isValid = NO;
    }
    
    // 验证广告配置
    DMConfigAdConfig *adConfig = [self adConfig];
    if (!adConfig) {
        [IMLogUtils error:IMLogTagError format:@"[DMConfigReader] 广告配置缺失"];
        isValid = NO;
    } else {
        if (!adConfig.default_sdk_type || adConfig.default_sdk_type.length == 0) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 默认SDK类型缺失"];
            isValid = NO;
        }
        
        if (!adConfig.IS_AppKey || adConfig.IS_AppKey.length == 0) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] IronSource AppKey缺失"];
        }
        
        if (!adConfig.Max_AppKey || adConfig.Max_AppKey.length == 0) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] MAX AppKey缺失"];
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 配置验证完成，结果: %@", isValid ? @"通过" : @"失败"];
    return isValid;
}


// 双广告位配置检查方法
+ (BOOL)hasDualAdConfiguration
{
    return [self hasDualRewardAdConfiguration] ||
           [self hasDualInterAdConfiguration] ||
           [self hasDualBannerAdConfiguration];
}

+ (BOOL)hasDualRewardAdConfiguration
{
    NSString *secondaryId = [self secondaryRewardAdUnitId];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

+ (BOOL)hasDualInterAdConfiguration
{
    NSString *secondaryId = [self secondaryInterAdUnitId];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

+ (BOOL)hasDualBannerAdConfiguration
{
    NSString *secondaryId = [self secondaryBannerAdUnitId];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

// MAX双广告位配置检查方法
+ (BOOL)hasDualAdConfigurationForMAX
{
    return [self hasDualRewardAdConfigurationForMAX] ||
           [self hasDualInterAdConfigurationForMAX] ||
           [self hasDualBannerAdConfigurationForMAX];
}

+ (BOOL)hasDualRewardAdConfigurationForMAX
{
    NSString *secondaryId = [self secondaryRewardAdUnitIdForMAX];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

+ (BOOL)hasDualInterAdConfigurationForMAX
{
    NSString *secondaryId = [self secondaryInterAdUnitIdForMAX];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

+ (BOOL)hasDualBannerAdConfigurationForMAX
{
    NSString *secondaryId = [self secondaryBannerAdUnitIdForMAX];
    return secondaryId && ![secondaryId isEqualToString:@""];
}

+ (BOOL)isDualAdConfigEnabled
{
    return [self hasDualAdConfiguration] || [self hasDualAdConfigurationForMAX];
}

#pragma mark - 双广告位ID获取方法

// 双广告位支持 - 主广告位ID
+ (NSString *)primaryRewardAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主激励广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *rewardIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"RewardIds"];
    if (!rewardIds || rewardIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] RewardIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in rewardIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主激励广告位ID(IS): %@", primaryId ?: @"空"];
            return primaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的激励广告配置"];
    return @"";
}

+ (NSString *)primaryInterAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主插屏广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *interIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"InterIds"];
    if (!interIds || interIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] InterIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in interIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主插屏广告位ID(IS): %@", primaryId ?: @"空"];
            return primaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的插屏广告配置"];
    return @"";
}

+ (NSString *)primaryBannerAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主横幅广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *bannerIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"BannerIds"];
    if (!bannerIds || bannerIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] BannerIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in bannerIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主横幅广告位ID(IS): %@", primaryId ?: @"空"];
            return primaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的横幅广告配置"];
    return @"";
}

// 双广告位支持 - 备用广告位ID
+ (NSString *)secondaryRewardAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用激励广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *rewardIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"RewardIds"];
    if (!rewardIds || rewardIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] RewardIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in rewardIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用激励广告位ID(IS): %@", secondaryId ?: @"空"];
            return secondaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的激励广告配置"];
    return @"";
}

+ (NSString *)secondaryInterAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用插屏广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *interIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"InterIds"];
    if (!interIds || interIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] InterIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in interIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用插屏广告位ID(IS): %@", secondaryId ?: @"空"];
            return secondaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的插屏广告配置"];
    return @"";
}

+ (NSString *)secondaryBannerAdUnitId {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用横幅广告位ID"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *bannerIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"BannerIds"];
    if (!bannerIds || bannerIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] BannerIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in bannerIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"IS"]) continue;
        
        BOOL isLow = [IMJSONUtils safeBoolFromDictionary:config forKey:@"is_low" defaultValue:YES];
        if (!isLow) {
            NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
            [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用横幅广告位ID(IS): %@", secondaryId ?: @"空"];
            return secondaryId ?: @"";
        }
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到非低价的横幅广告配置"];
    return @"";
}

// SDK配置文件方法
+ (NSString *)primaryRewardForSDKConfigFile{
    return [self primaryRewardAdUnitId];
}

+ (NSString *)secondaryRewardForSDKConfigFile {
    return [self secondaryRewardAdUnitId];
}
+ (NSString *)primaryInterForSDKConfigFile {
    return [self primaryInterAdUnitId];
}

+ (NSString *)secondaryInterForSDKConfigFile {
    return [self secondaryInterAdUnitId];
}
+ (NSString *)primaryBannerForSDKConfigFile {
    return [self primaryBannerAdUnitId];
}
+ (NSString *)secondaryBannerForSDKConfigFile {
    return [self secondaryBannerAdUnitId];
}

#pragma mark - MAX SDK配置文件方法

+ (NSString *)primaryRewardForSDKConfigFileMAX {
    return [self primaryRewardAdUnitIdForMAX];
}

+ (NSString *)secondaryRewardForSDKConfigFileMAX {
    return [self secondaryRewardAdUnitIdForMAX];
}

+ (NSString *)primaryInterForSDKConfigFileMAX {
    return [self primaryInterAdUnitIdForMAX];
}

+ (NSString *)secondaryInterForSDKConfigFileMAX {
    return [self secondaryInterAdUnitIdForMAX];
}

+ (NSString *)primaryBannerForSDKConfigFileMAX {
    return [self primaryBannerAdUnitIdForMAX];
}

+ (NSString *)secondaryBannerForSDKConfigFileMAX {
    return [self secondaryBannerAdUnitIdForMAX];
}

#pragma mark - MAX双广告位支持 - 主广告位ID

+ (NSString *)primaryRewardAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主激励广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *rewardIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"RewardIds"];
    if (!rewardIds || rewardIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] RewardIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in rewardIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        // 对于MAX，仅按类型匹配返回配置，不依赖is_low
        NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主激励广告位ID(MAX): %@", primaryId ?: @"空"];
        return primaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX激励广告配置"];
    return @"";
}

+ (NSString *)primaryInterAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主插屏广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *interIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"InterIds"];
    if (!interIds || interIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] InterIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in interIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主插屏广告位ID(MAX): %@", primaryId ?: @"空"];
        return primaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX插屏广告配置"];
    return @"";
}

+ (NSString *)primaryBannerAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取主横幅广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *bannerIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"BannerIds"];
    if (!bannerIds || bannerIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] BannerIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in bannerIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        NSString *primaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"primaryad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取主横幅广告位ID(MAX): %@", primaryId ?: @"空"];
        return primaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX横幅广告配置"];
    return @"";
}

#pragma mark - MAX双广告位支持 - 备用广告位ID

+ (NSString *)secondaryRewardAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用激励广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *rewardIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"RewardIds"];
    if (!rewardIds || rewardIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] RewardIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in rewardIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用激励广告位ID(MAX): %@", secondaryId ?: @"空"];
        return secondaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX激励广告配置"];
    return @"";
}

+ (NSString *)secondaryInterAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用插屏广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *interIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"InterIds"];
    if (!interIds || interIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] InterIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in interIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用插屏广告位ID(MAX): %@", secondaryId ?: @"空"];
        return secondaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX插屏广告配置"];
    return @"";
}

+ (NSString *)secondaryBannerAdUnitIdForMAX {
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (!reader.configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 配置数据未加载，无法获取备用横幅广告位ID(MAX)"];
        return @"";
    }
    
    NSDictionary *adConfig = [IMJSONUtils safeDictionaryFromDictionary:reader.configData forKey:@"ad_config"];
    if (!adConfig) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] ad_config配置不存在"];
        return @"";
    }
    
    NSArray *bannerIds = [IMJSONUtils safeArrayFromDictionary:adConfig forKey:@"BannerIds"];
    if (!bannerIds || bannerIds.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] BannerIds配置为空"];
        return @"";
    }
    
    for (NSDictionary *config in bannerIds) {
        if (![config isKindOfClass:[NSDictionary class]]) continue;
        
        NSString *adType = [IMJSONUtils safeStringFromDictionary:config forKey:@"ad_type"];
        if (![adType isEqualToString:@"MAX"]) continue;
        
        NSString *secondaryId = [IMJSONUtils safeStringFromDictionary:config forKey:@"secondad_unitID"];
        [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 获取备用横幅广告位ID(MAX): %@", secondaryId ?: @"空"];
        return secondaryId ?: @"";
    }
    
    [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] 未找到MAX横幅广告配置"];
    return @"";
}

/**
 * 获取全部IAP商品的产品ID（包含消耗品、非消耗品与订阅）
 * @return 产品ID数组（可能为空，按配置顺序且去重）
 */
- (nullable NSArray<NSString *> *)allIAPProductIds {
    [IMLogUtils debug:IMLogTagGeneral format:@"[DMConfigReader] 汇总全部IAP商品ID"];
    DMIAPConfig *config = [self iapConfig];
    if (!config) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[DMConfigReader] IAP配置不存在，无法获取全部商品ID"];
        return nil;
    }
    NSMutableOrderedSet<NSString *> *orderedIds = [NSMutableOrderedSet orderedSet];
    void (^appendIds)(NSArray<DMIAPProductConfig *> *) = ^(NSArray<DMIAPProductConfig *> *items) {
        for (DMIAPProductConfig *p in items) {
            NSString *pid = p.productId;
            if (pid && pid.length > 0) {
                [orderedIds addObject:pid];
            }
        }
    };
    // 按配置顺序合并：消耗品 -> 非消耗品 -> 订阅
    if (config.consumableIds.count > 0) { appendIds(config.consumableIds); }
    if (config.nonConsumableIds.count > 0) { appendIds(config.nonConsumableIds); }
    if (config.subscribeIds.count > 0) { appendIds(config.subscribeIds); }
    NSArray<NSString *> *result = orderedIds.array;
    [IMLogUtils info:IMLogTagGeneral format:@"[DMConfigReader] 全部IAP商品ID数量: %lu", (unsigned long)result.count];
    return result;
}

@end
